<?php

	include_once '../controladores/ControladorSecciones.php';
	include_once '../controladores/ControladorUsuarios.php';
	include_once '../controladores/ControladorAplicaciones.php';
	include_once '../controladores/ControladorImagenes.php';
	include_once '../clases/section.php';
	include_once '../config.inc.php';
	include_once 'resizeImage.php';
	
	if (!empty($_GET['user_id']) && !empty($_GET['app_id'])){
			$id = $_GET['user_id'];
			$idApp = $_GET['app_id'];
		}	 
	
	$command = new ControladorImagenes();
	$imageName = $command->searchImageName($idApp);
	
	$command = new ControladorUsuarios();
	$userEmail = $command->obtainUserEmail($id);
	
	$command = new ControladorAplicaciones();	
	$appName = $command->searchApplicationName($idApp);
		
		$targetApplication = ROUTE_APPLICATIONS_USERS.$userEmail."/Applications/".$appName;	
	
	$targetApplicationSections = $targetApplication."/sections/";		

	if (file_exists($targetApplicationSections)) deleteDir($targetApplicationSections);
	
	mkdir($targetApplicationSections);
	
	 $sCSS_Menu = '
	 <style type="text/css"> 
	 .nav{
					border:1px solid #ccc;
					border-width:1px 0;
					list-style:none;
					margin:0;
					padding:0;
					text-align:center;
				}
				.nav li{
					display:inline;
				}
				.nav a{
					display:inline-block;
					padding:10px;
				}	
	 </style>
	 <style type="text/css"> 
	  .thumb {
    height: 75px;
    border: 1px solid #000;
    margin: 10px 5px 0 0;
  }				
  </style>
';

					
		$sHTML_Header = '<!DOCTYPE html><html lang="es"><head>'.$sCSS_Menu.'</head><body>';			
		$sHTML_Footer =  '</body></html>'; 
			
	$command = new ControladorSecciones();
	$arraySections = $command->searchApplicationSectionsName($idApp);
	$sectionExample = new Section('','','','','');
	
		$sHTML_Content = "";				
		
		// Aqui se empiezan a pintar las secciones!
				
	for ($i = 0; $i < sizeof($arraySections); $i++){
		
		$sectionExample = $arraySections[$i];
		$command = new ControladorAplicaciones();
				
		$SaveFile = $targetApplicationSections.$sectionExample->getSecName().".html";
		
					$sHTML_Content = $sHTML_Content.$command->generarAplicacion($sectionExample->getAppId(),$sectionExample->getSecId(),$sectionExample->getSecName(),$targetApplication);
					
		$fh = fopen($SaveFile, "w") or die("can't open file");
		fwrite($fh,$sHTML_Header);
		fwrite($fh, $sHTML_Content);
		fwrite($fh, $sHTML_Footer);
		fclose($fh);
		
		$sHTML_Content = '';	
	}

	if (file_exists($appName)) deleteDir($appName);
	mkdir($appName);
	$androidTarget = $appName."/android";
	$iOSTarget = $appName."/iOS";
	$bbOSTarget = $appName."/bbos";
	mkdir($androidTarget);
	
	// Copiando estructura de proyectos a carpetas
	 
	 //***************************** Aplicación Android **********************************/
	 
	recurse_copy("android",$androidTarget);
	recurse_copy($targetApplication,$androidTarget."/assets/www/");
	
	$resize = new ResizeImage($targetApplication."/images/".$imageName);
	$resize->resizeTo(72,72, 'exact');	
	$iconApp = 'icon.png';
	$resize->saveImage($targetApplication."/images/".$iconApp);
				
	copy($targetApplication."/images/".$iconApp,$androidTarget."/res/drawable-hdpi/".strtolower($iconApp));
	copy($targetApplication."/images/".$iconApp,$androidTarget."/res/drawable-ldpi/".strtolower($iconApp));
	copy($targetApplication."/images/".$iconApp,$androidTarget."/res/drawable-mdpi/".strtolower($iconApp));
	copy($targetApplication."/images/".$iconApp,$androidTarget."/res/drawable-xhdpi/".strtolower($iconApp)); 
	
	$s = explode(".",$iconApp);
	
	modifyAndroidManifest($appName,strtolower($s[0]));
	modifyRfile($appName,strtolower($s[0]));
	
	
	//***************************** Aplicación iOS **********************************/
	
	recurse_copy("iOS",$iOSTarget);
	recurse_copy($targetApplication,$iOSTarget."/www/");
	
	$resize = new ResizeImage($targetApplication."/images/".$imageName);
	$resize->resizeTo(57,57, 'exact');	
	$resize->saveImage($iOSTarget.'/iOS/Resources/icons/icon.png');
	
	modifyPListFile($appName);
	
	//***************************** Aplicación Blackberry OS **********************************/
		
	recurse_copy("blackberry",$bbOSTarget);
	recurse_copy($targetApplication,$bbOSTarget."/www/");
	
	//Generando .zip de aplicaciones
	
	generateApplicationsZipFile($appName,$appName);	
?>

<?php

function recurse_copy($src,$dst) {

    $dir = opendir($src);

    @mkdir($dst);

    while(false !== ( $file = readdir($dir)) ) {

        if (( $file != '.' ) && ( $file != '..' )) {

            if ( is_dir($src . '/' . $file) ) {

                recurse_copy($src . '/' . $file,$dst . '/' . $file);

            }

            else {

                copy($src . '/' . $file,$dst . '/' . $file);

            }

        }

    }
    closedir($dir); 
}
?>

<?php

	function deleteDir($dir) 
	{ 
	   if (substr($dir, strlen($dir)-1, 1) != '/') 
		   $dir .= '/';  
	   if ($handle = opendir($dir)) 
	   { 
		   while ($obj = readdir($handle)) 
		   { 
			   if ($obj != '.' && $obj != '..') 
			   { 
				   if (is_dir($dir.$obj)) 
				   { 
					   if (!deleteDir($dir.$obj)) 
						   return false; 
				   } 
				   elseif (is_file($dir.$obj)) 
				   { 
					   if (!unlink($dir.$obj)) 
						   return false; 
				   } 
			   } 
		   } 
	
		   closedir($handle); 
	
		   if (!@rmdir($dir)) 
			   return false; 
		   return true; 
	   } 
	   return false; 
	} 

?>

<?php
	function generateApplicationsZipFile($folder,$appName){
		
		$output = $appName.".zip";
		$zip = new ZipArchive();
		 
		if ($zip->open($output, ZIPARCHIVE::CREATE) !== TRUE) {
			die ("Unable to open Archirve");
		}
		 
		$all= new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folder));
		 
		foreach ($all as $f=>$value) {
			$zip->addFile(realpath($f), $f) or die ("ERROR: Unable to add file: $f");
		}
		$zip->close();		
	}
?>


<?php 

 function modifyAndroidManifest($appName,$imgName){
	
	$manifest = '<?xml version="1.0" encoding="utf-8"?>
	<manifest xmlns:android="http://schemas.android.com/apk/res/android"
		package="com.cmsmetro.android"
		android:versionCode="1"
		android:versionName="1.0" >
	
		<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
	
		<supports-screens
			android:largeScreens="true"
			android:normalScreens="true"
			android:smallScreens="true"
			android:xlargeScreens="true"
			android:resizeable="true"
			android:anyDensity="true"
			/>
	
		<uses-permission android:name="android.permission.CAMERA" />
		<uses-permission android:name="android.permission.VIBRATE" />
		<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
		<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
		<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
		<uses-permission android:name="android.permission.INTERNET" />
		<uses-permission android:name="android.permission.RECEIVE_SMS" />
		<uses-permission android:name="android.permission.RECORD_AUDIO" />
		<uses-permission android:name="android.permission.RECORD_VIDEO"/>
		<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
		<uses-permission android:name="android.permission.READ_CONTACTS" />
		<uses-permission android:name="android.permission.WRITE_CONTACTS" />   
		<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />   
		<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
		<uses-permission android:name="android.permission.GET_ACCOUNTS" />
		<uses-permission android:name="android.permission.BROADCAST_STICKY" />
	
		<uses-feature android:name="android.hardware.camera" />
		<uses-feature android:name="android.hardware.camera.autofocus" />
	
		<application android:icon="@drawable/'.($imgName).'"
			android:label="'.$appName.'" >
			<activity android:configChanges="orientation|keyboardHidden" android:name=".AndroidActivity"
				android:label="'.$appName.'" >
				<intent-filter>
					<action android:name="android.intent.action.MAIN" />
	
					<category android:name="android.intent.category.LAUNCHER" />
				</intent-filter>
			</activity>
			<activity android:name="com.phonegap.DroidGap" android:label="'.$appName.'" 
					  android:configChanges="orientation|keyboardHidden">
				<intent-filter>
				</intent-filter>
			</activity>
		</application>
	
	</manifest>';
	
	file_put_contents("".$appName."/android/AndroidManifest.xml","");
	file_put_contents("".$appName."/android/AndroidManifest.xml",$manifest);
		
}
?>

<?php 

 function modifyRfile($appName,$imgName){
	
	$R = 'package com.cmsmetro.android;

			public final class R {
				public static final class attr {
				}
				public static final class drawable {
					public static final int ic_launcher=0x7f020000;
					public static final int '.$imgName.'=0x7f020001;
				}
				public static final class layout {
					public static final int main=0x7f030000;
				}
				public static final class string {
					public static final int app_name=0x7f050001;
					public static final int hello=0x7f050000;
				}
				public static final class xml {
					public static final int phonegap=0x7f040000;
					public static final int plugins=0x7f040001;
				}
			}
			';
	
	file_put_contents("".$appName."/android/gen/com/cmsmetro/android/R.java","");
	file_put_contents("".$appName."/android/gen/com/cmsmetro/android/R.java",$R);
		
}
?>

<?php
	function modifyPListFile($appName){
		
		$pListFile = '<?xml version="1.0" encoding="UTF-8"?>
	<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
	<plist version="1.0">
	<dict>
		<key>CFBundleIcons</key>
		<dict>
			<key>CFBundlePrimaryIcon</key>
			<dict>
				<key>CFBundleIconFiles</key>
				<array>
					<string>icon.png</string>
					<string>icon@2x.png</string>
					<string>icon-72.png</string>
					<string>icon-72@2x.png</string>
				</array>
				<key>UIPrerenderedIcon</key>
				<false/>
			</dict>
		</dict>
		<key>UISupportedInterfaceOrientations~ipad</key>
		<array>
			<string>UIInterfaceOrientationPortrait</string>
			<string>UIInterfaceOrientationLandscapeLeft</string>
			<string>UIInterfaceOrientationPortraitUpsideDown</string>
			<string>UIInterfaceOrientationLandscapeRight</string>
		</array>
		<key>UISupportedInterfaceOrientations</key>
		<array>
			<string>UIInterfaceOrientationPortrait</string>
		</array>
		<key>CFBundleDevelopmentRegion</key>
		<string>English</string>
		<key>CFBundleDisplayName</key>
		<string>'.$appName.'</string>
		<key>CFBundleExecutable</key>
		<string>${EXECUTABLE_NAME}</string>
		<key>CFBundleIconFile</key>
		<string>icon.png</string>
		<key>CFBundleIdentifier</key>
		<string>com.cmsmetro.iOS</string>
		<key>CFBundleInfoDictionaryVersion</key>
		<string>6.0</string>
		<key>CFBundleName</key>
		<string>${PRODUCT_NAME}</string>
		<key>CFBundlePackageType</key>
		<string>APPL</string>
		<key>CFBundleSignature</key>
		<string>????</string>
		<key>CFBundleVersion</key>
		<string>1.0</string>
		<key>LSRequiresIPhoneOS</key>
		<true/>
		<key>NSMainNibFile</key>
		<string></string>
		<key>NSMainNibFile~ipad</key>
		<string></string>
	</dict>
	</plist>
	';
	
	file_put_contents("".$appName."/iOS/iOS/iOS-Info.plist","");
	file_put_contents("".$appName."/iOS/iOS/iOS-Info.plist",$pListFile);

}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>MetroGenerador - Gestión de Secciones</title>
<link href="../estilos/style_index.css" rel="stylesheet" type="text/css" media="screen" />
<script>
	function showPreview(){
		$("#previewApp").show();
	}
</script><script type="text/javascript" src="../controladores/javascripts/jquery.min.js"></script>
</head>
<body>
<div id="header">
	<div id="logo"><img src="../imagenes/logo.png" alt="" width="335" height="53"/></div>
</div>
<div id="wrapper">
  <div id="page">
    <div id="content">
      <div class="post">
		    <h1 class="title"><a href="#">Tu aplicacion esta lista para ser descargada!</a>				</h1>
		    Aunque siempre es bueno tener el cuenta que se genera, puedes visualizar el previo de tu aplicación del lado izquierdo del banner!<br />
    
        <table width="852" border="0" align="center">
	          <tr>
	            <td width="198"><img src="../imagenes/bannerprevioapp.png" alt="" width="198" height="349" onclick="showPreview();"/></td>
	            <td width="163" align="left" id="previewApp" style="display:none"><div style="background-image: url(../imagenes/telefono.jpg); height: 485px; width: 244px; float:left; margin-right: -1.2em width: 38%;background-repeat: no-repeat; margin-left:auto"> <iframe src="<?php echo $appName?>/android/assets/www/sections/Bienvenida.html" align="center" style="background-color:white;height: 390px;width: 260px; margin:88px 33px; -ms-zoom: 0.68; -moz-transform: scale(0.68); -moz-transform-origin: 0 0; -o-transform: scale(0.75); -o-transform-origin: 0 0; -webkit-transform: scale(0.68); -webkit-transform-origin: 0 0;">
<br>Así lucirá la Aplicación.
</iframe></div></td>
	            <td width="477"><a href="<?php echo $appName.".zip";?>"><img src="../imagenes/mobile_devices_banner.jpg" alt="" width="477" height="255" /></a></td>
          </tr>
        </table>
        <p class="byline">&nbsp;</p>
		    <div class="entry"></div>
	  </div>
			<div class="post"></div>
	</div>
		<!-- end content -->
	<!-- start sidebars --><!-- end sidebars --></div>
	<!-- end page -->
</div>
</body>
</html>
